//
//  ProductAdvViewController.m
//  nonghubao
//
//  Created by 王 文彬 on 13-6-19.
//  Copyright (c) 2013年 Chongqing Nonghubao Co., Ltd. All rights reserved.
//

/*!
 @class
 @abstract 功能详情如下：
 1、实例化方法initWithData会接受服务器下发的：广告单价、账户余额、产品ID。
 2、用户填写要购买的天数。天数只接受整形，默认为1天。
 3、自动计算天数和广告单价的乘积，并与余额比较，如果超过余额，则提示用户。
 4、申请成功时，直接返回到产品列表页。失败时，停留在本页。
 5、用户点击返回按钮，直接退回产品列表页
 6、账户余额小于广告单价时，提示充值，并出现充值按钮。点击充值按钮present充值VC，充值VC关闭时，重新刷新页面上的数据
 
 本来采用UIWebView+HTML+Native方式混合开发。
 */

#import "ProductAdvViewController.h"
#import "Helper.h"
#import "Config.h"
#import "RechargeViewController.h"
#import "JSONRequest.h"
#import "JMFBase.h"

@interface ProductAdvViewController ()

@end


@implementation ProductAdvViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

/*!
 @method
 @abstract 通过参数数据实例化
 @param data 字典类型数据，应该包含广告单价、账户余额、产品ID
 @result 类实例
 */
- (id)initWithData:(NSDictionary *)data
{
    self = [super init];
    if (self) {
        _data = [NSMutableDictionary dictionaryWithDictionary:data];
        _advCheckingFlag = false;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = _L(@"vc_title_066");


    //导航栏左按钮：返回
    UIButton* backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    

    //使用一个UIScrollView来做self.view
    UIScrollView* scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, _SYS_FRAME_WIDTH, _SYS_FRAME_HEIGHT)];
    scrollView.contentSize = CGSizeMake(_SYS_FRAME_WIDTH, 600);
    scrollView.backgroundColor = _SYS_COLOR_BACKGROUND;
    self.view = scrollView;
    
    
    NSString* filePath = [[NSBundle mainBundle] pathForResource:@"product_adv" ofType:@"html"];
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, _SYS_FRAME_WIDTH, 460)];
    _webView.delegate = self;
    _webView.scrollView.scrollEnabled = false;
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];
    [self.view addSubview:_webView];
    
    
    UIButton* openButton = [[UIButton alloc] initWithFrame:CGRectMake(10, _webView.frame.size.height, 300, 40)];
    [openButton setBackgroundImage:[UIImage imageNamed:@"com_btn_018_n@2x"] forState:UIControlStateNormal];
    [openButton setTitle:_L(@"btn_yes_23") forState:UIControlStateNormal];
    [openButton addTarget:self action:@selector(openButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    openButton.titleLabel.font = _SYS_FONT_006;
    [self.view addSubview:openButton];
}


#pragma mark - 充值视图消失时，刷新页面数据
//////////////////////////////////////////////////////////////////
// 界面将要载入时，检查是否需要请求推广信息状态。业务为：
//  1）第一次界面将要打开时，数据源是直接通过initWithData方法输入的，不请求
//  2）当关闭充值VC时，应该重新请求，并刷新_data，再重新填充页面数据

/*!
 @method
 @abstract 视图将要显示时，检测请求标记，如果没有就发出请求，检查
 */
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    //如果检查标记为true，说明需要请求推广状态信息（非第一次载入）
    if (_advCheckingFlag) {

        JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_ADV_CHECK];
        request.delegate = self;
        request.hudOn = true;
        request.successSelector = @selector(advCheckSuccessSelector:);
        [request setValue:_data[@"id"] forParameter:@"productId"];
        [request asynchronous];
    }
    //否则说明是第一次载入，不需要新的请求，同时画一个菊花
    else {
        [Helper showAllTextDialog:_L(@"title_loading_01") inView:nil];
    }
}


/*!
 @method
 @abstract 检查推广信息状态时，请求成功的协议方法
 */
- (void)advCheckSuccessSelector:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        //组合参数
        NSMutableDictionary* data = [NSMutableDictionary dictionaryWithDictionary:jmf.data];
        [data setValue:_data[@"id"] forKey:@"id"];
        
        [_data removeAllObjects];
        _data = [NSMutableDictionary dictionaryWithDictionary:data];
        
        [self fillHtmlByData];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

////////////////////////////////////////////////////////////////


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - 返回按钮事件
/*!
 @method
 @abstract 返回到上一级
 @discussion 本页返回的上一级是商品列表，根据堆栈，即弹出到root即可
 */
- (void)backButtonEvent
{
    [self.navigationController popToViewController:self.navigationController.viewControllers[1] animated:true];
}


#pragma mark - UIWebViewDelegate
/*!
 @method
 @abstract 在HTML载入完成时，调用一次填充方法，将数据源里面的数据装入到页面中去
 */
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [self fillHtmlByData];
}


/*!
 @method
 @abstract 通过检测webView的跳转请求来检测按钮和链接的点击，并启动对应过程
 @discussion 'open:recharge' present充值页面
 */
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    //如果是充值页面被点击了
    if ([request.URL.relativeString isEqualToString:@"open:recharge"]) {
        //要设定检查标记为真，已使页面返回时，重新请求账户数据
        _advCheckingFlag = true;
        
        RechargeViewController* rechargeViewController = [[RechargeViewController alloc] init];
        
        UINavigationController* rechargeNavigationController = [[UINavigationController alloc] initWithRootViewController:rechargeViewController];
        [Helper navigationControllerCommonStyle:rechargeNavigationController];
        
        [self.navigationController presentModalViewController:rechargeNavigationController animated:true];
    }
    
    else if ([request.URL.relativeString isEqualToString:@"open:alert"]) {

        UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:@"" message:_L(@"alert_59") delegate:self cancelButtonTitle:_L(@"btn_yes_01") otherButtonTitles:nil];
        alerView.tag = 100;
        [alerView show];
    }

    return true;
}


#pragma mark - 使用数据源填充页面
/*!
 @method
 @abstract 使用数据源中数据，渲染HTML页面
 */
- (void)fillHtmlByData
{
    //填充可用余额
    [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById('balance').innerHTML='%.2f'", [_data[@"balance"] floatValue]]];
    
    //填充用户名字
#warning 1.6.4版之后打开注释
//    NSString* name = [[NSUserDefaults standardUserDefaults] stringForKey:@"accountName"];
//    name = name ? name : @"";
//    [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById('name').innerHTML='%@'", name]];
#warning 1.6.4版暂时用，之后版本，移除以下4行
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_U_GET_BASICINFO];
    [request setValue:_ACCOUNT_ID forParameter:@"userId"];
    NSDictionary* responseData = [request synchronous];
    [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById('name').innerHTML='%@'", responseData[@"data"][@"realName"]]];
    
    //填充单价
    [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById('adUnitPrice').innerHTML='%i'", [_data[@"adUnitPrice"] intValue]]];
    
    //填充费用
    [_webView stringByEvaluatingJavaScriptFromString:@"count();"];
}


#pragma mark - 开通按钮事件及请求
/*!
 @method
 @abstract 开通按钮被点击后出发的事件
 */
- (void)openButtonEvent
{
    NSNumber* day = [NSNumber numberWithInt:[[_webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('day').value"] intValue]];

    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_ADV_APPLY];
    request.delegate = self;
    request.hudOn = true;
    request.successSelector = @selector(advApplySuccessSelector:);
    [request setValue:day forParameter:@"day"];
    [request setValue:_data[@"id"] forParameter:@"productId"];
    [request asynchronous];
}


/*!
 @method
 @abstract 开通按钮点击后的请求成功后调用的方法
 */
- (void)advApplySuccessSelector:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        [Helper showAllTextDialog:_L(@"title_73") inView:nil];
        [self backButtonEvent];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}


@end